<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

function get_employee_titles() {
    return array('NR', 'NRTL', 'BS', 'BSTL', 'PG', 'PGTL', 'MedNR', 'MedBS', 'MedTL');
}

function get_all_titles() {
    return array('SD', 'HR', 'SC', 'RSM', 'KAM', 'SS', 'KAS', 'NR', 'NRTL', 'BS', 'BSTL', 'PG', 'PGTL', 'MedNR', 'MedBS', 'MedTL');
}

function get_manager_titles() {
    return array('SD', 'HR', 'SC', 'RSM', 'KAM', 'SS', 'KAS');
}

function show_human_title($title) {
    switch ($title) {
        case 'SD':
            echo 'Sale Director';
            break;
        case 'HR':
            echo 'HR Executive';
            break;
        case 'SC':
            echo 'SC Executive';
            break;

        case 'RSM':
            echo 'Regional Sales Manager';
            break;
        case 'KAM':
            echo 'Key Account Manager';
            break;
        case 'SS':
            echo 'Sales Supervisor';
            break;
        case 'KAS':
            echo 'Key Account Supervisor';
            break;

        case 'NR':
            echo 'Nutrition Representative';
            break;
        case 'NRTL':
            echo 'Nutrition Representative Team Leader';
            break;
        case 'PG':
            echo 'Promotion Girl';
            break;
        case 'PGTL':
            echo 'Promotion Girl Team Leader';
            break;
        case 'BS':
            echo 'Bone Scan';
            break;
        case 'BSTL':
            echo 'Bone Scan Team Leader';
            break;
        case 'MedNR':
            echo 'Medical Nutrition Representative';
            break;
        case 'MedBS':
            echo 'Medical Bone Scan';
            break;
        case 'MedTL':
            echo 'Medical Team Leader';
            break;
        default:
            echo 'Employee';
            break;
    }
}

function get_folder($title) {
    switch ($title) {
        case 'SD':
            return 'sd';
        case 'HR':
            return 'hr_sc';
        case 'SC':
            return 'hr_sc';

        case 'RSM':
            return 'rsm_kam';
        case 'KAM':
            return 'rsm_kam';
        case 'SS':
            return 'ss_kas';
        case 'KAS':
            return 'ss_kas';

        case 'NR':
            return 'user';
        case 'NRTL':
            return 'user';
        case 'PG':
            return 'user';
        case 'PGTL':
            return 'user';
        case 'BS':
            return 'user';
        case 'BSTL':
            return 'user';
        case 'MedNR':
            return 'user';
        case 'MedBS':
            return 'user';
        case 'MedTL':
            return 'user';
        default:
            return 'user';
    }
}

function color_attitude($score, $high, $medium, $rating) {
    if ($score >= $high) {
        return '<font color="green">' . $rating . '</font>';
    } else if ($score >= $medium) {
        return '<font color="blue">' . $rating . '</font>';
    } else {
        return '<font color="red">' . $rating . '</font>';
    }
}

function color_final_results($finalResultName) {
    switch ($finalResultName) {
        case 'Need Improvement':
            return '<font color="red">' . $finalResultName . '</font>';
            break;
        case 'Becoming Effective':
            return '<font color="#FFCC00">' . $finalResultName . '</font>';
            break;
        case 'Effective':
            return '<font color="green">' . $finalResultName . '</font>';
            break;
        case 'High Effective':
            return '<font color="blue">' . $finalResultName . '</font>';
            break;
        case 'Exceptional':
            return '<font color="#FF6600">' . $finalResultName . '</font>';
            break;
        default:
            return $finalResultName;
            break;
    }
}

function get_final_results(&$users, $eid, &$stat = array(), &$statForHR = array()) {
    $CI = get_instance();

    $CI->load->model('quiz_model', '', true);
    $CI->load->model('evaluation', '', true);
    $CI->load->model('saledetailresult', '', true);
    $CI->load->model('attitudedetailresult', '', true);
    $CI->load->model('finalrating', '', true);
    $CI->load->model('Settings', '', true);
    $settings = $CI->Settings->get(1);

    $CI->load->model('region', '', true);
    $regions = $CI->region->get_list();
    $regionDic = array();
    foreach ($regions as $key => $value) {
        $regionDic[$value['rsm_code']] = $value['region_name'];
    }

    // truy vấn kết quả làm bài nếu có
    // lấy kết quả bài test mới nhất (lần làm sau cùng) của từng nhân viên
    $lastQuizNR = $CI->quiz_model->get_last_of_group_and_evaluation(1, $eid);
    $lastQuizNRTL = $CI->quiz_model->get_last_of_group_and_evaluation(2, $eid);
    $lastQuizPG = $CI->quiz_model->get_last_of_group_and_evaluation(3, $eid);
    $lastQuizPGTL = $CI->quiz_model->get_last_of_group_and_evaluation(4, $eid);
    $lastQuizBS = $CI->quiz_model->get_last_of_group_and_evaluation(5, $eid);
    $lastQuizBSTL = $CI->quiz_model->get_last_of_group_and_evaluation(6, $eid);
    $lastQuizMedNR = $CI->quiz_model->get_last_of_group_and_evaluation(7, $eid);
    $lastQuizMedBS = $CI->quiz_model->get_last_of_group_and_evaluation(8, $eid);
    $lastQuizMedTL = $CI->quiz_model->get_last_of_group_and_evaluation(9, $eid);

    $ni = 0;
    $nimek = 0;
    $ninorth = 0;
    $nimt = 0;
    $nicentral = 0;
    $nimedical = 0;
    $nise = 0;
    $nihcm = 0;
    $be = 0;
    $bemek = 0;
    $benorth = 0;
    $bemt = 0;
    $becentral = 0;
    $bemedical = 0;
    $bese = 0;
    $behcm = 0;
    $ef = 0;
    $efmek = 0;
    $efnorth = 0;
    $efmt = 0;
    $efcentral = 0;
    $efmedical = 0;
    $efse = 0;
    $efhcm = 0;
    $he = 0;
    $hemek = 0;
    $henorth = 0;
    $hemt = 0;
    $hecentral = 0;
    $hemedical = 0;
    $hese = 0;
    $hehcm = 0;
    $ex = 0;
    $exmek = 0;
    $exnorth = 0;
    $exmt = 0;
    $excentral = 0;
    $exmedical = 0;
    $exse = 0;
    $exhcm = 0;

    foreach ($users as &$eachUser) {

        $quid = 0;
        switch ($eachUser['title']) {
            case 'NR':
                $quid = $lastQuizNR['quid'];
                break;
            case 'NRTL':
                $quid = $lastQuizNRTL['quid'];
                break;
            case 'PG':
                $quid = $lastQuizPG['quid'];
                break;
            case 'PGTL':
                $quid = $lastQuizPGTL['quid'];
                break;
            case 'BS':
                $quid = $lastQuizBS['quid'];
                break;
            case 'BSTL':
                $quid = $lastQuizBSTL['quid'];
                break;
            case 'MedNR':
                $quid = $lastQuizMedNR['quid'];
                break;
            case 'MedBS':
                $quid = $lastQuizMedBS['quid'];
                break;
            case 'MedTL':
                $quid = $lastQuizMedTL['quid'];
                break;
        }
        $result = $CI->result_model->get_last($quid, $eachUser['id']);
        $eachUser['testResult'] = $result;
        if ($result != false) {
            $eachUser['testResult']['number_of_attempt'] = $CI->quiz_model->get_number_of_attempt($quid, $eachUser['id']);
        }
        $eachUser['testInfo'] = $CI->quiz_model->get($quid);

        // kết quả sale
        $saleResult = $CI->saledetailresult->get_wheres(array('user_code' => $eachUser['code'], 'eid' => $eid));
        $eachUser['saleResult'] = $saleResult;

        // first rating
        if ($eachUser['testResult']['number_of_attempt'] > 0 && $saleResult != false) {
            $firstScore = $eachUser['testResult']['percentage'] * $settings['test_ratio'] + $saleResult['score'] * $settings['sale_ratio'];
            if ($firstScore >= $settings['ni'] && $firstScore < $settings['be']) {
                $eachUser['firstRating']['id'] = 1;
                $eachUser['firstRating']['name'] = 'Need Improvement';
            } else if ($firstScore >= $settings['be']) {
                $eachUser['firstRating']['id'] = 2;
                $eachUser['firstRating']['name'] = 'Becoming Effective';
            } else if ($firstScore >= $settings['ef']) {
                $eachUser['firstRating']['id'] = 3;
                $eachUser['firstRating']['name'] = 'Effective';
            } else if ($firstScore >= $settings['he']) {
                $eachUser['firstRating']['id'] = 4;
                $eachUser['firstRating']['name'] = 'High Effective';
            } else if ($firstScore >= $settings['ex']) {
                $eachUser['firstRating']['id'] = 5;
                $eachUser['firstRating']['name'] = 'Exceptional';
            }
        } else {
            $eachUser['firstRating'] = false;
        }

        // kết quả thái độ
        $attResult = $CI->attitudedetailresult->get_wheres(array('user_id' => $eachUser['id'], 'eid' => $eid));
        $eachUser['attResult'] = $attResult;

        // final rating
        if ($eachUser['firstRating'] && $attResult) {
            $finalRating = $CI->finalrating->get_wheres(array('art_id' => $eachUser['attResult']['art_id'], 'frt_id' => $eachUser['firstRating']['id']));
            $eachUser['finalRating'] = $finalRating;
            switch ($finalRating['name']) {
                case 'Need Improvement':
                    $ni++;
                    switch ($regionDic[$eachUser['rsm_code']]) {
                        case 'MEKONG':
                            $nimek++;
                            break;
                        case 'NORTH':
                            $ninorth++;
                            break;
                        case 'MT':
                            $nimt++;
                            break;
                        case 'CENTRAL':
                            $nicentral++;
                            break;
                        case 'MEDICAL':
                            $nimedical++;
                            break;
                        case 'SOUTH EAST':
                            $nise++;
                            break;
                        case 'HCM':
                            $nihcm++;
                            break;
                    }
                    break;
                case 'Becoming Effective':
                    $be++;
                    switch ($regionDic[$eachUser['rsm_code']]) {
                        case 'MEKONG':
                            $bemek++;
                            break;
                        case 'NORTH':
                            $benorth++;
                            break;
                        case 'MT':
                            $bemt++;
                            break;
                        case 'CENTRAL':
                            $becentral++;
                            break;
                        case 'MEDICAL':
                            $bemedical++;
                            break;
                        case 'SOUTH EAST':
                            $bese++;
                            break;
                        case 'HCM':
                            $behcm++;
                            break;
                    }
                    break;
                case 'Effective':
                    $ef++;
                    switch ($regionDic[$eachUser['rsm_code']]) {
                        case 'MEKONG':
                            $efmek++;
                            break;
                        case 'NORTH':
                            $efnorth++;
                            break;
                        case 'MT':
                            $efmt++;
                            break;
                        case 'CENTRAL':
                            $efcentral++;
                            break;
                        case 'MEDICAL':
                            $efmedical++;
                            break;
                        case 'SOUTH EAST':
                            $efse++;
                            break;
                        case 'HCM':
                            $efhcm++;
                            break;
                    }
                    break;
                case 'High Effective':
                    $he++;
                    switch ($regionDic[$eachUser['rsm_code']]) {
                        case 'MEKONG':
                            $hemek++;
                            break;
                        case 'NORTH':
                            $henorth++;
                            break;
                        case 'MT':
                            $hemt++;
                            break;
                        case 'CENTRAL':
                            $hecentral++;
                            break;
                        case 'MEDICAL':
                            $hemedical++;
                            break;
                        case 'SOUTH EAST':
                            $hese++;
                            break;
                        case 'HCM':
                            $hehcm++;
                            break;
                    }
                    break;
                case 'Exceptional':
                    $ex++;
                    switch ($regionDic[$eachUser['rsm_code']]) {
                        case 'MEKONG':
                            $efmek++;
                            break;
                        case 'NORTH':
                            $efnorth++;
                            break;
                        case 'MT':
                            $efmt++;
                            break;
                        case 'CENTRAL':
                            $efcentral++;
                            break;
                        case 'MEDICAL':
                            $efmedical++;
                            break;
                        case 'SOUTH EAST':
                            $efse++;
                            break;
                        case 'HCM':
                            $efhcm++;
                            break;
                    }
                    break;
                default:
                    break;
            }
        } else {
            $eachUser['finalRating'] = false;
        }
    }

    $stat['ni'] = $ni;
    $stat['be'] = $be;
    $stat['ef'] = $ef;
    $stat['he'] = $he;
    $stat['ex'] = $ex;

    $statForHR['nimek'] = $nimek;
    $statForHR['ninorth'] = $ninorth;
    $statForHR['nimt'] = $nimt;
    $statForHR['nicentral'] = $nicentral;
    $statForHR['nimedical'] = $nimedical;
    $statForHR['nise'] = $nise;
    $statForHR['nihcm'] = $nihcm;
    $statForHR['bemek'] = $bemek;
    $statForHR['benorth'] = $benorth;
    $statForHR['bemt'] = $bemt;
    $statForHR['becentral'] = $becentral;
    $statForHR['bemedical'] = $bemedical;
    $statForHR['bese'] = $bese;
    $statForHR['behcm'] = $behcm;
    $statForHR['efmek'] = $efmek;
    $statForHR['efnorth'] = $efnorth;
    $statForHR['efmt'] = $efmt;
    $statForHR['efcentral'] = $efcentral;
    $statForHR['efmedical'] = $efmedical;
    $statForHR['efse'] = $efse;
    $statForHR['efhcm'] = $efhcm;
    $statForHR['hemek'] = $hemek;
    $statForHR['henorth'] = $henorth;
    $statForHR['hemt'] = $hemt;
    $statForHR['hecentral'] = $hecentral;
    $statForHR['hemedical'] = $hemedical;
    $statForHR['hese'] = $hese;
    $statForHR['hehcm'] = $hehcm;
    $statForHR['efmek'] = $exmek;
    $statForHR['exnorth'] = $exnorth;
    $statForHR['exmt'] = $exmt;
    $statForHR['excentral'] = $excentral;
    $statForHR['exmedical'] = $exmedical;
    $statForHR['exse'] = $exse;
    $statForHR['exhcm'] = $exhcm;

    return $users;
}

function array2csv(array &$array) {
    if (count($array) == 0) {
        return null;
    }
    ob_start();
    $df = fopen("php://output", 'w');
    fputcsv($df, array_keys(reset($array)));
    foreach ($array as $row) {
        fputcsv($df, $row);
    }
    fclose($df);
    return ob_get_clean();
}

function ConvertToCSV($array, $AddFirstHeaderName = '') {
    $CSVString = "";
    $Keys = array();
    foreach ($array as $eachTransaction) {
        $Keys = array_keys($eachTransaction);
        break;
    }


    $CSVString .= ($AddFirstHeaderName != '' ? '"Date",' : '') . '"' . implode('","', $Keys) . "\"\n";

    foreach ($array as $Key => $Value) {
        if ($AddFirstHeaderName != '') {
            $CSVString .= "\"" . $Key . "\",";
        }
        foreach ($Value as $Stat) {
            $CSVString .= "\"" . $Stat . "\",";
        }
        $CSVString = substr($CSVString, 0, -1);
        $CSVString .= "\n";
    }

    return $CSVString;
}

function download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

/*
  http://stackoverflow.com/questions/6101956/generating-a-random-password-in-php
 */

function randomPassword($passLength = 8) {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < $passLength; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

function create_email() {
    //$this->load->library('My_PHPMailer');
    $CI = & get_instance();
    $CI->load->library('My_PHPMailer'); // load library 
    $CI->load->model('Settings', '', true);
    $settings = $CI->Settings->get(1);

    $mail = new PHPMailer();
    $mail->CharSet = 'UTF-8';
    $mail->IsSMTP(); // we are going to use SMTP
    $mail->SMTPAuth = true; // enabled SMTP authentication
    $mail->SMTPSecure = $settings['smtp_sec'];  // prefix for secure protocol to connect to the server
    $mail->Host = $settings['smtp_host'];      // setting GMail as our SMTP server
    //$mail->SMTPDebug  = 2;
    $mail->Port = $settings['smtp_port'];                   // SMTP port to connect to GMail 465 26
    $mail->Username = $settings['smtp_username'];  // user email address
    $mail->Password = $settings['smtp_password'];            // password in GMail

    $mail->SetFrom($settings['from_email'], $settings['from_name']);  //Who is sending the email
    $mail->AddReplyTo($settings['from_email'], $settings['from_name']);  //email address that receives the response

    return $mail;
}

function send_mail_do_again($emailAddress, $name, $quizInfo) {
    $mail = create_email();

    $mail->Subject = "Fonterra - Cho Phép Làm Lại Bài Trắc Nghiệm";
    $message = "Bạn đã được cho phép làm lại bài trắc nghiệm, " . $quizInfo['quiz_name'] . ".";
    $mail->Body = $message;
    $mail->AltBody = $message;

    $destino = $emailAddress; // Who is addressed the email to
    $mail->AddAddress($destino, $name);

//        $mail->AddAttachment("images/phpmailer.gif");      // some attached files
//        $mail->AddAttachment("images/phpmailer_mini.gif"); // as many as you want
    if (!$mail->Send()) {
        $message = "Error: " . $mail->ErrorInfo;
    } else {
        $message = "Message sent correctly!";
    }
    return $message;
    //$this->load->view('sent_mail',$data);
}

function send_mail_reject($emailAddress, $name, $employee, $evaluation = null) {
    $mail = create_email();

    $mail->Subject = "Fonterra - Từ Chối Kết Quả Đánh Giá Thái Độ";
    $message = "Kết quả đánh giá thái độ của nhân viên " . $employee['name'] . ", mã nhân viên " . $employee['code']
            . ", ". $employee['title'] ." đã bị từ chối. Bạn vui lòng kiểm tra và đánh giá lại cho nhân viên này.";
    $mail->Body = $message;
    $mail->AltBody = $message;

    $destino = $emailAddress; // Who is addressed the email to
    $mail->AddAddress($destino, $name);

//        $mail->AddAttachment("images/phpmailer.gif");      // some attached files
//        $mail->AddAttachment("images/phpmailer_mini.gif"); // as many as you want
    if (!$mail->Send()) {
        $message = "Error: " . $mail->ErrorInfo;
    } else {
        $message = "Message sent correctly!";
    }
    return $message;
    //$this->load->view('sent_mail',$data);
}

function send_mail_password($emailAddress, $name, $username, $password) {
    $mail = create_email();

    $mail->IsHTML(true);
    $mail->Subject = "PM Đánh giá nhân sự - Thiết lập lại mật khẩu";
    $message = "Chúng tôi tạo ra mật khẩu mới dựa trên yêu cầu của bạn.<br/>
        Tên đăng nhập: " . $username . "<br/>
        Mật khẩu mới: " . $password;
    $mail->Body = $message;
    $mail->AltBody = $message;

    $destino = $emailAddress; // Who is addressed the email to
    $mail->AddAddress($destino, $name);

//        $mail->AddAttachment("images/phpmailer.gif");      // some attached files
//        $mail->AddAttachment("images/phpmailer_mini.gif"); // as many as you want
    if (!$mail->Send()) {
        $message = "Error: " . $mail->ErrorInfo;
    } else {
        $message = "Message sent correctly!";
    }
    return $message;
    //$this->load->view('sent_mail',$data);
}

function send_mail_confirm_change_password($emailAddress, $name, $username, $link) {
    $mail = create_email();

    $mail->IsHTML(true);
    $mail->Subject = "PM Đánh giá nhân sự - Quên mật khẩu";
    $message = "Chúng tôi đã nhận được yêu cầu thiết lập lại mật khẩu của bạn. Để thiết lập lại mật khẩu của bạn, hãy truy cập vào liên kết dưới đây.<br/>
        Tên đăng nhập:" . $username . "<br/>
        Mật khẩu liên kết: <a href=\"$link\">$link</a>";
    $mail->Body = $message;
    $mail->AltBody = $message;

    $destino = $emailAddress; // Who is addressed the email to
    $mail->AddAddress($destino, $name);

//        $mail->AddAttachment("images/phpmailer.gif");      // some attached files
//        $mail->AddAttachment("images/phpmailer_mini.gif"); // as many as you want
    if (!$mail->Send()) {
        $message = "Error: " . $mail->ErrorInfo;
    } else {
        $message = "Message sent correctly!";
    }
    return $message;
    //$this->load->view('sent_mail',$data);
}

function getUploadData() {
    
    // trước khi gọi nhớ load trong controller
    //$this->load->helper('xlsimport/php-excel-reader/excel_reader2');
    //$this->load->helper('xlsimport/spreadsheetreader.php');
    
    if (isset($_FILES['xlsfile'])) {
                $targets = 'xls/';
                $targets = $targets . basename($_FILES['xlsfile']['name']);
                $docadd = ($_FILES['xlsfile']['name']);
                if (move_uploaded_file($_FILES['xlsfile']['tmp_name'], $targets)) {
                    $Filepath = $targets;
                    $allxlsdata = array();
                    date_default_timezone_set('UTC');

                    $StartMem = memory_get_usage();

                    try {
                        $Spreadsheet = new SpreadsheetReader($Filepath);
                        $BaseMem = memory_get_usage();

                        $Sheets = $Spreadsheet->Sheets();

                        foreach ($Sheets as $Index => $Name) {

                            $Time = microtime(true);

                            $Spreadsheet->ChangeSheet($Index);

                            // chỉ lấy dữ liệu sheet đầu tiên. Nếu muốn lấy nhiều sheet và bỏ qua sheet trống -> count($Spreadsheet) > 0
                            if($Index > 0)
                            {
                                break;
                            }

                            foreach ($Spreadsheet as $Key => $Row) {
                                //echo $Key.': ';
                                if ($Row) {
                                    //print_r($Row);
                                    $allxlsdata[] = $Row;
                                } else {
                                    //var_dump($Row);
                                }
                                $CurrentMem = memory_get_usage();

                                if ($Key && ($Key % 500 == 0)) {
                                }
                            }
                        }
                    } catch (Exception $E) {
                        echo $E->getMessage();
                        return false;
                    }

                    return $allxlsdata;
                }
            } else {
                echo "Error: " . $_FILES["file"]["error"];
                return false;
            }
}